package com.zhangtai.modules.controller.admin;


import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.controller.aouthLogin.MemberLoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.EmployeeOverworkOodDao;
import com.zhangtai.modules.dao.EmployeeOverworkSubOddDao;
import com.zhangtai.modules.dto.OverworkOodDto;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeOverworkOodEntity;
import com.zhangtai.modules.entity.employee.EmployeeOverworkSubOddEntity;
import com.zhangtai.modules.service.employee.EmployeeOverworkOodService;
import com.zhangtai.modules.service.employee.EmployeeOverworkSubOddService;
import com.zhangtai.modules.vo.EmployeeOverworkOodVo;
import com.zhangtai.utils.*;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;


/**
 *
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2020-12-15 17:01:39
 */
@Api(tags="自助员工零星加班")
@RestController
@RequestMapping("employeeOverworkOdd")
@Slf4j
public class EmployeeOverworkOodController {
    @Autowired
    private EmployeeOverworkOodService employeeOverworkOodService;
    @Autowired
    private EmployeeOverworkSubOddService employeeOverworkSubOodService;
    @Autowired
    private LoginController loginController;
    @Autowired
    private MemberLoginController memberLoginController;
    @Autowired
    private EmployeeOverworkSubOddDao employeeOverworkSubOddDao;
    @Autowired
    private EmployeeOverworkOodDao employeeOverworkOodDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;

    /**
     * Hr端分页查询-零星加班申请
     */
    @GetMapping("/listOverWorkOdd")
    @ApiOperation("Hr端分页查询-零星加班申请")
    public R<PageResult<EmployeeOverworkOodVo>> list(@RequestParam(value = "oprationName",required = false) String oprationName,
                  @RequestParam(value = "orgName",required = false) String orgName,
                  @RequestParam(value = "unitName",required = false)String unitName, HttpServletRequest request
            , @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
        R uR = loginController.getUserInfo(request);
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        PageResult<EmployeeOverworkOodVo> result = employeeOverworkOodService
                .getOddOverWorkList(oprationName,orgName,unitName,pageNum,pageSize,orgIds);
        return R.ok(result);
    }


    /**
     * Hr端分页查询-零星加班申请
     */
    @GetMapping("/listOddMember")
    @ApiOperation("自助端分页查询-零星加班")
    public R<PageResult<OverworkOodDto>> listMember(HttpServletRequest request
            , @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
//        JSONObject data = memberLoginController.getUserInfo(request).getData();
//        if (ObjectUtils.isEmpty(data)){
//            return R.error("请先登录");
//        }
//
//        String usercode = data.getString("usercode"); //只能查询自己的信息
        String usercode = "ZT028817";
        Page<OverworkOodDto> page =  new Page<OverworkOodDto>(pageNum,pageSize);

        List<OverworkOodDto> dtos= employeeOverworkOodDao.getOddDto(usercode,page);
        if(!CollectionUtils.isEmpty(dtos)){
            page.setRecords(dtos);
        }
        return R.ok(page);
    }

//
    /**
     * Hr端根据id查询
     */
    @GetMapping("/getOddById")
    @ApiOperation("Hr端根据id查询-零星加班申请")
    public R<EmployeeOverworkOodVo> info(@RequestParam("id") String id){
        EmployeeOverworkOodEntity employeeOverworkOod = employeeOverworkOodService.getByIdE(new Long(id));
        EmployeeOverworkOodVo employeeOverworkOodVo = BeanUtilsMabach.doToDto(employeeOverworkOod, EmployeeOverworkOodVo.class);

        List<EmployeeOverworkSubOddEntity> subOddEntities = employeeOverworkSubOddDao
                .getSubOddByteooid(employeeOverworkOod.getId());
        if(!CollectionUtils.isEmpty(subOddEntities)){
            employeeOverworkOodVo.setList(subOddEntities);
        }

        return R.ok(employeeOverworkOodVo);
    }

    /**
     * 保存
     */
    @PostMapping("/saveOdd")
    @ApiOperation("Hr端保存 新增or修改-零星加班申请")
    @Transactional
    public R save(@RequestBody EmployeeOverworkOodVo employeeOverworkOodVo,HttpServletRequest request) throws Exception {
        EmployeeOverworkOodEntity entity = BeanUtilsMabach
                .dtoToDo(employeeOverworkOodVo, EmployeeOverworkOodEntity.class);
        EmployeeOverworkOodEntity byIdE = employeeOverworkOodService.getByIdE(entity.getId());
        R uR = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) uR.getData();
        Long orgId = user.getLong("orgId");
        Long unitId = user.getLong("depId");
        Long jobId = user.getLong("jobId");
        Long oid =user.getLong("id");
        String usercode = user.getString("usercode");
        entity.setStatus(0);
        entity.setOrgId(orgId);
        entity.setUnitId(unitId);
        entity.setJobId(jobId);
        entity.setOprationId(usercode);
        entity.setOid(oid);
        entity.setCreateTime(new Date());
        Long id =snowflakeIdWorker.nextId();
        entity.setId(id);

        List<EmployeeOverworkSubOddEntity> list = employeeOverworkOodVo.getList();

        if(byIdE!=null){
            //更新
            employeeOverworkOodDao.deleteById(byIdE.getId());
            List<EmployeeOverworkSubOddEntity> subOddEntities = employeeOverworkSubOddDao
                    .selectList(new QueryWrapper<EmployeeOverworkSubOddEntity>()
                    .eq("teoo_id", byIdE.getId()));
            if(!CollectionUtils.isEmpty(subOddEntities)){
                for (EmployeeOverworkSubOddEntity subOddEntity:subOddEntities
                        ) {

                    employeeOverworkSubOddDao.deleteById(subOddEntity.getId());
                }
            }
        }
            //新增
            entity.setIsDelete(0);
            employeeOverworkOodService.saveE(entity);
            if (!CollectionUtils.isEmpty(list)) {
                for (EmployeeOverworkSubOddEntity subOddEntity : list
                        ) {
                    subOddEntity.setIsDelete(0);
                    subOddEntity.setTeooId(id);
                    EmployeeInfoEntity infoEntity = employeeInfoDao
                            .selectOne(new QueryWrapper<EmployeeInfoEntity>()
                            .eq("name", subOddEntity.getUserName()));
                    if(infoEntity!=null) {
                        subOddEntity.setOrgId(infoEntity.getOrgId());
                        subOddEntity.setUnitId(infoEntity.getUnitId());
                        subOddEntity.setOid(infoEntity.getOid());
                        subOddEntity.setUserId(infoEntity.getCode());
                    }
                    employeeOverworkSubOodService.saveE(subOddEntity);
                }


        }
        return R.ok();
    }


    /*
     * 删除
     */
    @DeleteMapping("/deleteOdd")
    @ApiOperation("Hr端保存 删除-零星加班申请")
    @Transactional
    public R delete(@RequestParam String id){

        employeeOverworkOodService.removeOneById(new Long(id));


        List<EmployeeOverworkSubOddEntity> subOddByteooids = employeeOverworkSubOddDao.getSubOddByteooid(new Long(id));
        if(!CollectionUtils.isEmpty(subOddByteooids)) {
            for (EmployeeOverworkSubOddEntity item: subOddByteooids
                 ) {
                employeeOverworkSubOodService.removeOneById(item.getId());

            }
        }
        return R.ok();
    }

}